from django.shortcuts import render

# Create your views here.
from django_redis import get_redis_connection
from rest_framework.response import Response
from rest_framework.views import APIView

from order.models import OrderInfo
from pay.models import Payment

from rest_framework.permissions import IsAuthenticated
from rest_framework import status
class PaymentAPIView(APIView):
    permission_classes = [IsAuthenticated]
    def get(self,request,order_id):
        try:
            order = OrderInfo.objects.get(order_id=order_id,
                                          user=request.user,
                                          status=OrderInfo.ORDER_STATUS_ENUM['UNPAID'])
        except OrderInfo.DoesNotExist:
            return Response(status=status.HTTP_400_BAD_REQUEST)
        from alipay import AliPay
        from mall import settings
        app_private_key_string = open(settings.APP_PRIVATE_KEY_PATH).read()
        alipay_public_key_string = open(settings.ALIPAY_PUBLIC_KEY_PATH).read()
        alipay = AliPay(
            appid=settings.ALIPAY_APPID,
            app_notify_url=None,
            app_private_key_string=app_private_key_string,
            alipay_public_key_string=alipay_public_key_string,
            sign_type="RSA2",
            debug=settings.ALIPAY_DEBUG
        )
        subject = '测试订单'
        order_string = alipay.api_alipay_trade_page_pay(
            out_trade_no=order_id,
            total_amount=str(order.total_amount),
            subject=subject,
            return_url="http://www.meiduo.site:8080/pay_success.html"
        )
        alipay_url = settings.ALIPAY_URL+'?'+order_string
        print(alipay_url)
        return Response({'alipay_url':alipay_url})


class PayStatuAPIView(APIView):
    def put(self,request):
        # 1.接收查询字符串参数
        # 2.根据支付宝文档进行数据的验证
        # 3.如果验证成功则获取 支付宝流水号和订单id
        # 4.将支付宝流水号和订单id 保存起来
        # 5.更新订单状态
        data = request.query_params.dict()
        # print(data)
        signature = data.pop('sign')
        # print(signature)
        from alipay import AliPay
        from mall import settings
        app_private_key_string = open(settings.APP_PRIVATE_KEY_PATH).read()
        alipay_public_key_string = open(settings.ALIPAY_PUBLIC_KEY_PATH).read()

        alipay = AliPay(
            appid=settings.ALIPAY_APPID,
            app_notify_url=None,  # 默认回调url
            app_private_key_string=app_private_key_string,
            # 支付宝的公钥，验证支付宝回传消息使用，不是你自己的公钥,
            alipay_public_key_string=alipay_public_key_string,
            sign_type="RSA2",  # RSA 或者 RSA2
            debug=settings.ALIPAY_DEBUG  # 默认False
        )
        success = alipay.verify(data,signature)
        if success:
            trade_no = data.get('trade_no')
            out_trade_no = data.get('out_trade_no')
            Payment.objects.create(
                order_id = out_trade_no,
                trade_id = trade_no
            )
            OrderInfo.objects.filter(order_id=out_trade_no).update(status=OrderInfo.ORDER_STATUS_ENUM['UNSEND'])
            return Response({'trade_id':trade_no})







